package io.xxx.xbutler.core.callback;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.xxx.xbutler.data.RobotMapper;
import io.xxx.xbutler.domain.Callback;
import io.xxx.xbutler.domain.GenderType;
import io.xxx.xbutler.domain.Robot;
import io.xxx.xbutler.domain.RobotType;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * 登录成功回调
 * <p>
 * 登录成功后，会回调给商家此回调；但是机器人的个人信息会取缓存数据，最新个人信息数据需要通过机器人个人信息补充回调更新；
 * <p>
 * 商家扫码号第一次登录至开放平台后会进行初始化数据，首次初始化时间比较长，根据机器人的数据量一般需要1-5分钟处理完初始化，初始化过程中会分步推送机器人的基础数据给商家，首次登录成功后商家需要耐心等待。
 *
 * <pre>
 * {
 *     "Data": {
 *         "nSex": 1,
 *         "vcCity": "Zhangjiajie",
 *         "nIsLimit": 0,
 *         "nLogType": 0,
 *         "vcDevice": "C96A382962224A1C7CFFB522D06ACEE8",
 *         "nTrueName": 0,
 *         "vcCountry": "CN",
 *         "vcWhatsUp": "志存高远",
 *         "vcWxAlias": "dengbin19910916",
 *         "nLoginType": 10,
 *         "time_stamp": 1737779507514,
 *         "vcNickName": "邓斌",
 *         "vcProvince": "Hunan",
 *         "vcRobotWxId": "wxid_arpszpwvw10n21",
 *         "vcHeadImgUrl": "https://wx.qlogo.cn/mmhead/ver_1/duL6P7rffIVRFfBVpF6OlfQHqeQiblgPeKCQ1Qsy91KLZNj6nC9rYY98JcWsa2KgYicwq0JJPzkn5UK0sQpYxaibwdwBfdjKmwD3FbKwBiajs59YX9R3PK1xnuUu8aODojoD/132",
 *         "user_serial_no": "MTRCQzI2QzFGMjNBNzdBMDc3NjA2NzIxNDYxODBBRjU6MQ==",
 *         "vcPersonQRCode": "",
 *         "source_order_no": "",
 *         "vcBase64WhatsUp": "5b+X5a2Y6auY6L+c",
 *         "vcRobotSerialNo": "14BC26C1F23A77A07760672146180AF5",
 *         "vcBase64NickName": "6YKT5paM",
 *         "relation_serial_no": "",
 *         "vcRelationSerialNo": "",
 *         "IsAllowJoinBigChatRoom": false
 *     },
 *     "nType": 1003,
 *     "nResult": 1,
 *     "vcResult": "Success",
 *     "nTimeStamp": 1737779509321,
 *     "vcSerialNo": "20250125123049985113919500454",
 *     "vcRobotWxId": "wxid_arpszpwvw10n21",
 *     "vcMerchantNo": "202407150008480",
 *     "vcRobotSerialNo": "14BC26C1F23A77A07760672146180AF5"
 * }
 *
 * {
 *     "Data": {
 *         "nSex": 0,
 *         "vcCity": null,
 *         "nIsLimit": 0,
 *         "nLogType": 0,
 *         "vcDevice": "EF41BC9078E7A401DA0A69C2C60283B7",
 *         "nTrueName": 1,
 *         "vcCountry": null,
 *         "vcWhatsUp": "",
 *         "vcWxAlias": "nme3ykpt",
 *         "nLoginType": 10,
 *         "time_stamp": 1738019563490,
 *         "vcNickName": "季娣",
 *         "vcProvince": null,
 *         "vcRobotWxId": "wxid_qjbzvqalzm6p22",
 *         "vcHeadImgUrl": "https://wx.qlogo.cn/mmhead/ver_1/HicM4aSVGfx6OicbXat2OUWCY4nHgjXRJLVKjod6ZazmwpS71bDXUosCAYIkXHGxLgCRnpbqrgiaWl1BZyheiazE9ZVLhvzaqoqaFAAdMMsagVYyqupJoSZHTovc69vGh8lr/132",
 *         "user_serial_no": "MEMwMjY1QkEzOTk4QjQzNTY3OUIzMjcwRjJERTVBRTU6Mg==",
 *         "vcPersonQRCode": "http://kfpt-file.oss-cn-hangzhou.aliyuncs.com/not-expired/wechat-ios-protocol/pt/robot-qr-code/merchant/20241218/0c0265ba3998b435679b3270f2de5ae5.jpg",
 *         "source_order_no": "",
 *         "vcBase64WhatsUp": "",
 *         "vcRobotSerialNo": "0C0265BA3998B435679B3270F2DE5AE5",
 *         "vcBase64NickName": "5a2j5aij",
 *         "relation_serial_no": "",
 *         "vcRelationSerialNo": "",
 *         "IsAllowJoinBigChatRoom": true
 *     },
 *     "nType": 1003,
 *     "nResult": 1,
 *     "vcResult": "Success",
 *     "nTimeStamp": 1738019565226,
 *     "vcSerialNo": "20250120114318217449510144024",
 *     "vcRobotWxId": "wxid_qjbzvqalzm6p22",
 *     "vcMerchantNo": "202407150008480",
 *     "vcRobotSerialNo": "0C0265BA3998B435679B3270F2DE5AE5"
 * }
 * </pre>
 */
@Slf4j
@Component
public class _1003Handler implements CallbackHandler {

    @Resource
    private RobotMapper robotMapper;

    @Override
    public String name() {
        return "登录成功回调";
    }

    @Override
    public boolean supports(int type) {
        return type == 1003;
    }

    @Override
    public void handle(Callback callback) {
        LocalDateTime now = LocalDateTime.now();
        String robotId = callback.getRobotId();
        JSONObject data = (JSONObject) callback.getData();

        Robot robot = (Robot) new Robot()
                .setTrueName(data.getInteger("nTrueName"))   // nTrueName
                .setQrcode(data.getString("vcPersonQRCode"))
                .setDeviceId(data.getString("vcDevice"))    // vcDevice
                .setAllowJoinBigRoom(data.getBoolean("IsAllowJoinBigChatRoom"))  // IsAllowJoinBigChatRoom
                .setLimited(data.getInteger("nIsLimit") != 0)
                .setOnline(true)
                .setLoginType(data.getInteger("nLoginType"))
                .setLogType(data.getInteger("nLogType"))
                .setId(robotId)
                .setSerialNo(callback.getSerialNo())
                .setName(data.getString("vcNickName"))
                .setBase64Name(data.getString("vcBase64NickName"))
                .setGender(GenderType.valueOf(data.getIntValue("nSex")))
                .setAlias(data.getString("vcWxAlias"))
                .setAvatar(data.getString("vcHeadImgUrl"))
                .setWhatsUp(data.getString("vcWhatsUp"))
                .setBase64WhatsUp(data.getString("vcBase64WhatsUp"))
                .setProvince(data.getString("vcProvince"))
                .setCity(data.getString("vcCity"))
                .setCounty(data.getString("vcCountry"))
                .setUpdatedTime(now);

        boolean exists = isExists(robotId);
        if (exists) {
            robotMapper.updateById(robot);
        } else {
            robot.setTodayJoinNum(5)
                    .setTodayJoinedNum(0)
                    .setMaxJoinNum(30)
                    .setJoinedNum(0)
                    .setMaxAddFriendNum(50)
                    .setAddedFriendNum(0)
                    .setTodayAddFriendNum(10)
                    .setTodayAddedFriendNum(0)
                    .setAutoAllowJoinRoom(false)
                    .setAutoAllowAddFriend(false)
                    .setType(RobotType.WECHAT)
                    .setCreatedTime(now);
            robotMapper.insert(robot);
        }
    }

    private boolean isExists(String robotId) {
        LambdaQueryWrapper<Robot> wrapper = new LambdaQueryWrapper<Robot>()
                .eq(Robot::getId, robotId);
        return robotMapper.exists(wrapper);
    }
}
